package com.blockmeta.bbs.immodule.activity;

import android.view.View;

import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.TimeUtil;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.activity.base.BaseIMSearchHomeActivity;
import com.blockmeta.bbs.immodule.adapter.IMSearchNormalResultAdapter;
import com.blockmeta.bbs.immodule.bean.IMSearchNormalPOJO;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.dao.ChatMessage;
import com.blockmeta.bbs.immodule.dao.IMUserEntity;
import com.blockmeta.bbs.immodule.utils.IMUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.functions.Function;

/**
 * @author airthor
 * @date 2020/5/13
 * im搜索通用搜索结果返回页面
 */
public class IMSearchNormalResultActivity extends BaseIMSearchHomeActivity implements BaseQuickAdapter.RequestLoadMoreListener {
    public static final int HAS_MORE_SIZE = 4;
    private List<IMSearchNormalPOJO> mSearchNormalResultList = new ArrayList<>(40);
    private IMSearchNormalResultAdapter mResultAdapter;
    private String mKeyWords;
    private int mPage = 1;
    @Override
    protected void initialize() {
        super.initialize();
        mEdtSearchInput.setHint("搜索聊天内容");
    }

    @Override
    protected BaseQuickAdapter<IMSearchNormalPOJO, BaseViewHolder> getAdapter() {
        if (mResultAdapter==null) {
            mResultAdapter = new IMSearchNormalResultAdapter(mSearchNormalResultList);
            mResultAdapter.setOnLoadMoreListener(this,mRcvSearchList);
        }
        return mResultAdapter;
    }

    @Override
    protected void searchOnNet(String content) {
        mKeyWords = content;
        mPage = 1;
        mSearchNormalResultList.clear();
        mResultAdapter.notifyDataSetChanged();

        Flowable<List<IMSearchNormalPOJO>> friendFlowable = Flowable.just(IMApplicationContext.getUserDomainService().searchFriendPaged(content,4,0,"",""))
                .flatMap(new Function<List<IMUserEntity>, Flowable<List<IMSearchNormalPOJO>>>() {
                    @Override
                    public Flowable<List<IMSearchNormalPOJO>> apply(List<IMUserEntity> imUserEntities){
                        if (imUserEntities.size()==0){
                            return Flowable.empty();
                        }
                        List<IMSearchNormalPOJO> friends = new ArrayList<>(8);
                        IMSearchNormalPOJO pojo = new IMSearchNormalPOJO();
                        pojo.itemType = IMSearchNormalPOJO.DIVIDER;
                        pojo.dividerTitle = "好友";
                        friends.add(pojo);

                        for (IMUserEntity imUserEntity : imUserEntities) {
                            IMSearchNormalPOJO imSearchNormalPOJO = new IMSearchNormalPOJO();
                            imSearchNormalPOJO.avator = imUserEntity.getAvatarPath();
                            imSearchNormalPOJO.name = imUserEntity.getName();
                            imSearchNormalPOJO.id = imUserEntity.getUserId();
                            imSearchNormalPOJO.peopleGrade = IMUtils.UserLevel.getUserLevel(imUserEntity.getUserLevel()).getValue();
                            imSearchNormalPOJO.boatAge = TimeUtil.getUserRegisterAge(imUserEntity.getDate());
                            imSearchNormalPOJO.itemType = IMSearchNormalPOJO.FRIEND;
                            imSearchNormalPOJO.keyWord = mKeyWords;
                            friends.add(imSearchNormalPOJO);
                        }

                        if (imUserEntities.size()==HAS_MORE_SIZE){
                            IMSearchNormalPOJO pojo1 = new IMSearchNormalPOJO();
                            pojo1.itemType = IMSearchNormalPOJO.MORE;
                            pojo1.whichHasMore = IMSearchNormalPOJO.FRIEND;
                            pojo1.keyWord = mKeyWords;
                            friends.add(pojo1);
                        }
                        return Flowable.just(friends);
                    }
                });
        Flowable<List<IMSearchNormalPOJO>> circleFlowable = Flowable.just(IMApplicationContext.getUserDomainService().searchCirclePaged(content,4,0,"",""))
                .flatMap(new Function<List<IMUserEntity>, Flowable<List<IMSearchNormalPOJO>>>() {

                    @Override
                    public Flowable<List<IMSearchNormalPOJO>> apply(List<IMUserEntity> imUserEntities) {
                        if (imUserEntities.size()==0){
                            return Flowable.empty();
                        }

                        List<IMSearchNormalPOJO> circles = new ArrayList<>(8);

                        IMSearchNormalPOJO pojo = new IMSearchNormalPOJO();
                        pojo.itemType = IMSearchNormalPOJO.DIVIDER;
                        pojo.dividerTitle = "圈子";
                        circles.add(pojo);

                        for (IMUserEntity imUserEntity : imUserEntities) {
                            IMSearchNormalPOJO imSearchNormalPOJO = new IMSearchNormalPOJO();
                            imSearchNormalPOJO.avator = imUserEntity.getAvatarPath();
                            imSearchNormalPOJO.name = imUserEntity.getName();
                            imSearchNormalPOJO.id = imUserEntity.getUserId();
                            imSearchNormalPOJO.circleGrade = FormatUtil.parseInt(imUserEntity.getGroupLevel());
                            imSearchNormalPOJO.circleSize = imUserEntity.getGroupCount() + " 人";
                            imSearchNormalPOJO.circleKind = IMUtils.getCircleClass(imUserEntity.getCircleClass());
                            imSearchNormalPOJO.itemType = IMSearchNormalPOJO.CIRCLE;
                            imSearchNormalPOJO.keyWord = mKeyWords;
                            circles.add(imSearchNormalPOJO);
                        }

                        if (imUserEntities.size()==HAS_MORE_SIZE){
                            IMSearchNormalPOJO pojo1 = new IMSearchNormalPOJO();
                            pojo1.itemType = IMSearchNormalPOJO.MORE;
                            pojo1.keyWord = mKeyWords;
                            circles.add(pojo1);
                        }
                        return Flowable.just(circles);
                    }
                });
        Flowable<List<IMSearchNormalPOJO>> sessionFLowable= Flowable.just(IMApplicationContext.getChatMessageDomainService().searchChatMessagePaged(content,10,0,"",""))
                .flatMap(new Function<List<ChatMessage>, Flowable<List<IMSearchNormalPOJO>>>() {

                    @Override
                    public Flowable<List<IMSearchNormalPOJO>> apply(List<ChatMessage> chatMessages) {
                        if(chatMessages.size()==0){
                            return Flowable.empty();
                        }
                        List<IMSearchNormalPOJO> sessions = new ArrayList<>(16);

                        IMSearchNormalPOJO pojo = new IMSearchNormalPOJO();
                        pojo.itemType = IMSearchNormalPOJO.DIVIDER;
                        pojo.dividerTitle = "聊天消息";
                        sessions.add(pojo);

                        for (ChatMessage chatMessage : chatMessages) {
                            IMSearchNormalPOJO imSearchNormalPOJO = new IMSearchNormalPOJO();
                            imSearchNormalPOJO.mChatMessage = chatMessage;
                            imSearchNormalPOJO.itemType = IMSearchNormalPOJO.SESSION;
                            imSearchNormalPOJO.keyWord = mKeyWords;
                            sessions.add(imSearchNormalPOJO);
                        }
                        return Flowable.just(sessions);
                    }
                });

        Flowable.concat(circleFlowable,friendFlowable,sessionFLowable)
                .compose(RxUtil.<List<IMSearchNormalPOJO>>rxSchedulerHelper())
                .compose(this.<List<IMSearchNormalPOJO>>bindToLifecycle())
                .subscribe(new IMSubscriber<List<IMSearchNormalPOJO>>(mContext) {
                    @Override
                    public void onNext(List<IMSearchNormalPOJO> imSearchNormalPOJOS) {
                        mSearchNormalResultList.addAll(imSearchNormalPOJOS);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mResultAdapter.notifyDataSetChanged();
                        mResultAdapter.disableLoadMoreIfNotFullPage();
                    }
                });
    }

    @Override
    protected View setEmptyView() {
        return getLayoutInflater().inflate(R.layout.empty_search_for_im,null);
    }

    @Override
    public void netWorkComplete() {
        mGroupGoSearch.setVisibility(View.GONE);
        mRcvSearchList.setVisibility(View.VISIBLE);
        if (getAdapter().getEmptyView() == null && setEmptyView() != null) {
            getAdapter().setEmptyView(setEmptyView());
        }
    }

    /**
     * 已无更多数据
     */
    protected void loadMorEnd(){
        if (mResultAdapter!=null&&mResultAdapter.isLoading()) {
            mResultAdapter.loadMoreEnd();
        }
    }

    /**
     * 加载更多已完成
     */
    protected void loadMoreComplete(){
        if (mResultAdapter!=null&&mResultAdapter.isLoading()){
            mResultAdapter.loadMoreComplete();
        }
    }
    /**
     * 加载更多失败
     */
    protected void loadMoreFail(){
        if (mResultAdapter!=null&&mResultAdapter.isLoading()){
            mResultAdapter.loadMoreFail();
        }
    }

    @Override
    public void onLoadMoreRequested() {
        Flowable.just(IMApplicationContext.getChatMessageDomainService().searchChatMessagePaged(mKeyWords,10,mPage,"",""))
                .flatMap(new Function<List<ChatMessage>, Flowable<List<IMSearchNormalPOJO>>>() {

                    @Override
                    public Flowable<List<IMSearchNormalPOJO>> apply(List<ChatMessage> chatMessages) {
                        if(chatMessages.size()==0){
                            return Flowable.empty();
                        }
                        List<IMSearchNormalPOJO> sessions = new ArrayList<>(16);

                        for (ChatMessage chatMessage : chatMessages) {
                            IMSearchNormalPOJO imSearchNormalPOJO = new IMSearchNormalPOJO();
                            imSearchNormalPOJO.mChatMessage = chatMessage;
                            imSearchNormalPOJO.itemType = IMSearchNormalPOJO.SESSION;
                            imSearchNormalPOJO.keyWord = mKeyWords;
                            sessions.add(imSearchNormalPOJO);
                        }
                        return Flowable.just(sessions);
                    }
                })
                .compose(RxUtil.<List<IMSearchNormalPOJO>>rxSchedulerHelper())
                .compose(this.<List<IMSearchNormalPOJO>>bindToLifecycle())
                .defaultIfEmpty(new ArrayList<IMSearchNormalPOJO>() {
                })
                .subscribe(new IMSubscriber<List<IMSearchNormalPOJO>>(mContext) {
                    @Override
                    public void onNext(List<IMSearchNormalPOJO> imSearchNormalPOJOS) {
                        if (imSearchNormalPOJOS.size()==0){
                            loadMorEnd();
                        }else {
                            mPage++;
                            loadMoreComplete();
                        }
                        mSearchNormalResultList.addAll(imSearchNormalPOJOS);
                        mResultAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        loadMoreFail();
                    }
                });
    }
}
